# -*- coding: utf-8 -*-  
from email import encoders
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import smtplib
import base64
import StringIO

#from io import StringIO      #python3

def send_email(from_email, to_emails, subject, body_html, attachments=[], cc=[], bcc=[], attachments2=[]):
    attachment_ready_html = []
    img_id = 0
    mime_images = []
    # iterate over raw HTML
    for l in body_html:
        # For each image in the body_html, convert each to a base64 encoded inline image
        if l.startswith("<img"):
            image_data = l[len("<img src='data:image/png;base64,"):-2]
            mime_img = MIMEImage(base64.standard_b64decode(image_data))
            mime_img.add_header('Content-ID', '<img-%d>' % img_id)
            attachment_ready_html.append("<center><img src='cid:img-%d'></center>" % img_id)
            img_id += 1
            mime_images.append(mime_img)
        else:
            attachment_ready_html.append(l)
    print("Added {} images".format(img_id))

    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = ", ".join(to_emails)
    body = MIMEText('\n'.join(attachment_ready_html), 'html')

    for i in mime_images:
      msg.attach(i)

    msg.attach(body)

    for raw_attachment in attachments:
        attachment = MIMEApplication(open(raw_attachment, 'rb').read())
        attachment.add_header('Content-Disposition', 'attachment', filename=raw_attachment)
        msg.attach(attachment)

    for raw_attachment in attachments2:
        att1 = MIMEText(raw_attachment["content"].getvalue(), 'base64', 'utf-8')
        #att1 = MIMEText(raw_attachment["content"], 'base64', 'utf-8')      #for python3
        att1["Content-Type"] = raw_attachment["type"]
        att1["Content-Disposition"] = 'attachment; filename="%s"' % raw_attachment["name"]
        msg.attach(att1)

    send_by_sendgrid(to_emails, msg)

def send_by_sendgrid(to_emails, msg):
    mail_host="smtp.sendgrid.net"
    mail_user="apikey"
    mail_pass="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"
    sender = msg['From']
    smtpObj = smtplib.SMTP() 
    smtpObj.connect(mail_host, 25)    # 25 为 SMTP 端口号
    smtpObj.login(mail_user, mail_pass) 
    smtpObj.sendmail(sender, to_emails, msg.as_string())  
    smtpObj.quit() 
    print("Sending Email.")

def export_as_csv(field_names, list):
    # define field_names as above, assuming your indentation is correct
    csv_buffer = StringIO.StringIO()
    #csv_buffer = StringIO()        #for python3
    #print(field_names)
    csv_buffer.write(','.join(field_names))
    csv_buffer.write('\r\n')

    for row in list:
        csv_buffer.write(','.join(row))
        csv_buffer.write('\r\n')
    return csv_buffer

if __name__ == "__main__":
    html = [
        "<center><h1>Example Email Title</h1></center>",
        """
        <p><b>A standard paragraph.</b></p>
        <ol>
            <li>This demonstrates a list.</li>
        </ol>
        """,
        "<img src='' />"
    ]
    html.extend([
        "<br>"
        " Some more",
        "<p>items go here</p>"
    ])
    #attachments = ['./send_email.py']
    attachments = []
    content = export_as_csv(
        ["Account Type", "Account Num", "SubAccount", "Reason why didn't purchase online"],
        [
            ["T-Member", "730", "0", ""]
        ]
    )
    attachments2 = [
        {"name": "nocredit_jobPreview.csv", "content": content, "type":"text/csv"},
    ]

    from_addr = "ifelse01@126.com"
    to_addrs = [
        "miragelu@seekasia.com",
        "person2@gmail.com"
    ]
    subject = "A Fantastic Databricks Report"
    
    send_email(from_addr, to_addrs, subject, html, attachments, attachments2 = attachments2)